import { Router } from 'express'
import { renderToString } from 'react-dom/server'
import createApp from 'create-app/lib/server'
import routes from '../src'
import * as devEnv from '../build/setup-dev-env'
import config from '../server.config'
import * as $helpers from './helpers'

const router = Router()

const paths = routes.map(route => route.path)

export default router

const serverAppSettings = {
  loader: module => module.default || module,
  routes,
  viewEngine: {
    render: renderToString
  }
}

let app = createApp(serverAppSettings)

let assets = {}

if (process.env.NODE_ENV === 'development') {
  router.use((req, res, next) => {
    assets = getAssets(res.locals.webpackStats.toJson().assetsByChunkName)
    next()
  })
  // 在开发模式下，服务端热更新拿到当前最新的路由映射表
  devEnv.setupServer({
    handleHotModule: newRoutes => {
      app = createApp({
        ...serverAppSettings,
        routes: newRoutes
      })
    }
  })
}

router.all('*', async (req, res, next) => {
  const basename = req.basename || ''
  try {
    const { content, controller } = await app.render(req.url, {
      isServer: true,
      isClient: false,
      basename: basename,
      paths,
      preload: {},
      res,
    })
    if (!content) {
      return
    }
    let publicPath = '/static'
    if (basename) {
      publicPath = basename + publicPath
    }
    res.render('index', {
      title: 'ISOMORPHISM',
      content,
      assets,
      publicPath,
      appSettings: {
        basename,
        // can add more property to the client
      }
    })
  } catch (error) {
    next(error)
  }
})

function getAssets(stats) {
  return Object.keys(stats).reduce((result, assetName) => {
    const value = stats[assetName]
    result[assetName] = Array.isArray(value) ? value[0] : value
    return result
  }, {})
}
